package com.file.system.controller.system;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.file.system.entity.dict.IsSuperAdmin;
import com.file.system.entity.res.BaseCode;
import com.file.system.entity.res.CommonResult;
import com.file.system.entity.res.DataPage;
import com.file.system.entity.system.WebDepartmentUser;
import com.file.system.entity.system.WebUser;
import com.file.system.plugin.shiro.ShiroTools;
import com.file.system.service.system.IWebDepartmentUserService;
import com.file.system.service.system.IWebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Objects;

import static cn.hutool.core.util.ObjectUtil.isNotEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotNull;
import static cn.hutool.crypto.digest.DigestUtil.md5Hex;


/**
 * 账号
 *
 * @author jch
 */
@RestController
@Validated
@RequestMapping("/web/user")
public class WebUserController {

    @Autowired
    private IWebUserService service;
    @Autowired
    private IWebDepartmentUserService iWebDepartmentUserService;

    /**
     * 查询账号分页
     *
     * @param pageIndex 页数|1
     * @param pageSize  每页条数|10
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/page/{pageIndex}/{pageSize}")
    public CommonResult<DataPage<List<WebUser>>> page(@PathVariable
                                                      @Min(value = 1, message = "页数最小1")
                                                      Integer pageIndex,
                                                      @PathVariable
                                                      @Min(value = 1, message = "每页条数最小1")
                                                      @Max(value = 100, message = "每页条数最大100")
                                                      Integer pageSize,
                                                      @RequestBody @Validated WebUser webUser
    ) {
        QueryWrapper<WebUser> query = new QueryWrapper<>();
        //排序
        query.orderByDesc("a.id");
        //查询条件
        query.eq("a.is_del", 0);
        //用户名
        query.like(isNotEmpty(webUser.getName()), "a.name", webUser.getName());
        //用户名
        query.like(isNotEmpty(webUser.getUsername()), "a.username", webUser.getUsername());
        //手机号
        query.like(isNotEmpty(webUser.getPhone()), "a.phone", webUser.getPhone());
        //邮箱
        query.like(isNotEmpty(webUser.getEmail()), "a.email", webUser.getEmail());
        //字典状态
        query.eq(isNotEmpty(webUser.getDictOnOff()), "a.dict_on_off", webUser.getDictOnOff());
        //所属部门条件
        query.eq(isNotNull(webUser.getFkDepartmentId()), "b.fk_department_id", webUser.getFkDepartmentId());
        //查询集合
        DataPage<List<WebUser>> dp = service.page(pageIndex, pageSize, query);

        return CommonResult.ok().setResult(dp);
    }


    /**
     * 通过id查询账号
     *
     * @param id 账号id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/id/{id}")
    public CommonResult<WebUser> getById(@PathVariable
                                         @Min(value = 1, message = "id长度最小1")
                                         Long id) {
        //查询集合
        WebUser webUser = service.getById(id);
        return CommonResult.ok().setResult(webUser);
    }

    /**
     * 通过ids查询账号集合
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listByIds")
    public CommonResult<List<WebUser>> listByIds(@RequestBody List<Long> ids) {
        //查询集合
        List<WebUser> list = service.listByIds(ids);
        return CommonResult.ok().setResult(list);
    }


    /**
     * 查询所有非删除状态账号
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/listAll")
    public CommonResult<List<WebUser>> listAll() {
        //查询集合
        List<WebUser> list = service.listAll();
        return CommonResult.ok().setResult(list);
    }


    /**
     * 通过id删除账号
     *
     * @param id id
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/remove/{id}")
    public CommonResult removeById(@PathVariable
                                   @Min(value = 1, message = "id长度最小1")
                                   Long id) {
        WebUser webOldUser = service.getById(id);
        //判断是否是系统账号
        if (ObjectUtil.equal(webOldUser.getIsSuperAdmin(), IsSuperAdmin.YES.val)) {
            return CommonResult.fail().setText("系统账号无法删除");
        }
        //删除
        boolean state = service.removeById(id);
        //返回
        return CommonResult.check(state);
    }

    /**
     * 通过ids删除账号
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/removeByIds")
    public CommonResult removeById(@RequestBody List<Long> ids) {
        //返回
        return CommonResult.check(service.removeByIds(ids));
    }


    /**
     * 通过id编辑账号
     *
     * @param webUser 账号
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/updateById")
    public CommonResult<WebUser> updateById(@RequestBody @Validated(WebUser.update.class) WebUser webUser) {

        WebUser webOldUser = service.getById(webUser.getId());
        // 判断是否是系统账号
        if (ObjectUtil.equal(webOldUser.getIsSuperAdmin(), IsSuperAdmin.YES.val)) {
            return CommonResult.fail().setText("系统账号无法编辑");
        }
        // 判断用户名是否修改
        if (StrUtil.isNotEmpty(webUser.getUsername()) && ObjectUtil.notEqual(webUser.getUsername(), webOldUser.getUsername())) {
            int count = service.count(new QueryWrapper<WebUser>()
                    .eq("a.is_del", 0)
                    .eq("a.username", webUser.getUsername())
            );
            if (count > 0) return CommonResult.fail().setText("用户名存在");
        }
        // 判断电话号码是否修改
        if (StrUtil.isNotEmpty(webUser.getPhone()) && ObjectUtil.notEqual(webUser.getPhone(), webOldUser.getPhone())) {
            int count = service.count(new QueryWrapper<WebUser>()
                    .eq("a.is_del", 0)
                    .eq("a.phone", webUser.getPhone())
            );
            if (count > 0) return CommonResult.fail().setText("电话号码存在");
        }
        // 判断邮箱地址是否修改
        if (StrUtil.isNotEmpty(webUser.getEmail()) && ObjectUtil.notEqual(webUser.getEmail(), webOldUser.getEmail())) {
            int count = service.count(new QueryWrapper<WebUser>()
                    .eq("a.is_del", 0)
                    .eq("a.email", webUser.getEmail())
            );
            if (count > 0) return CommonResult.fail().setText("邮箱地址存在");
        }
        // 判断是否开启邮箱验证

        boolean state = service.updateById(webUser);
        return CommonResult.check(state).setResult(webUser);
    }


    /**
     * 添加账号
     *
     * @param webUser 账号
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @PostMapping("/save")
    public CommonResult<WebUser> save(@RequestBody @Validated(WebUser.add.class) WebUser webUser) {
        //检查username
        int count = service.count(new QueryWrapper<WebUser>()
                .eq("a.is_del", 0)
                .eq("a.username", webUser.getUsername())
        );
        if (count > 0) return CommonResult.fail().setText("用户名存在");
        //检查phone
        if (isNotEmpty(webUser.getPhone())) {
            count = service.count(new QueryWrapper<WebUser>()
                    .eq("a.is_del", 0)
                    .eq("a.phone", webUser.getPhone())
            );
            if (count > 0) return CommonResult.fail().setText("电话号码存在");
        }
        //检查email
        if (isNotEmpty(webUser.getEmail())) {
            count = service.count(new QueryWrapper<WebUser>()
                    .eq("a.is_del", 0)
                    .eq("a.email", webUser.getEmail())
            );
            if (count > 0) return CommonResult.fail().setText("邮箱地址存在");
        }

        webUser.setPassword(md5Hex(md5Hex(webUser.getUsername())));
        webUser.setIsSuperAdmin("0");
        //添加账号
        boolean state = service.save(webUser);
        if (!state) {
            return CommonResult.fail().setText("新增用户失败");
        }
        //所属部门条件
        if (isNotNull(webUser.getFkDepartmentId())) {
            //添加部门用户关联
            WebDepartmentUser departmentUser = new WebDepartmentUser();
            departmentUser.setFkDepartmentId(webUser.getFkDepartmentId());
            departmentUser.setFkUserId(webUser.getId());
            state = iWebDepartmentUserService.save(departmentUser);
            if (!state) {
                return CommonResult.fail().setText("添加部门关联失败");
            }
        }
        return CommonResult.check(state).setResult(webUser);
    }


    /**
     * 修改个人密码
     *
     * @param webUser 用户密码
     * @return CommonResult
     * @apiNote -
     * @author 靳春晖
     */
    @PostMapping("/password")
    public CommonResult<WebUser> modifyPassword(@RequestBody @Validated(WebUser.password.class) WebUser webUser) {
        WebUser user = ShiroTools.getShiroUser();
        if (Objects.isNull(user)) {
            return CommonResult.fail(BaseCode.Common.USER_NOT_LOGIN);
        }
        webUser.setPassword(md5Hex(webUser.getNewPassword()));
        webUser.setOldPassword(md5Hex(webUser.getOldPassword()));

        // 判断原密码是否正确
        if (ObjectUtil.notEqual(webUser.getOldPassword(), user.getPassword())) {
            return CommonResult.fail().setText("原密码错误");
        }
        // 判断新旧密码是否相同
        if (ObjectUtil.equal(webUser.getPassword(), user.getPassword())) {
            return CommonResult.fail().setText("新旧密相同");
        }

        // 设置用户id
        webUser.setId(user.getId());
        boolean state = service.updateById(webUser);
        return CommonResult.check(state);
    }


    /**
     * 重置密码
     *
     * @param webUser 用户id
     * @return webUser CommonResult
     * @apiNote -
     * @author 靳春晖
     */
    @PostMapping("/reset")
    public CommonResult<WebUser> reset(@RequestBody @Validated(WebUser.reset.class) WebUser webUser) {
        //获取WebUser对象
        WebUser webuser = service.getById(webUser.getId());
        //如果WebUser对象不存在，返回CommonResult.fail()
        if (ObjectUtil.isNull(webuser)) return CommonResult.fail();
        //对密码进行md5加密
        webuser.setPassword(md5Hex(md5Hex(webuser.getUsername())));
        //更新WebUser对象
        boolean state = service.updateById(webuser);
        //返回CommonResult对象
        return CommonResult.check(state).setResult(webuser);
    }
}

